'''
Created on Nov 19, 2012

@author: kafkef
'''

from dexen.system.common.base import Action, Individual


action_mgrs = {}

def GetActionMgr(job_info):
    global action_mgrs
    if not action_mgrs.has_key(job_info):
        action_mgrs[job_info] = ActionMgr()
    return action_mgrs[job_info]

def GetAllActionMgrs():
    return action_mgrs

def clear():
    action_mgrs.clear()

def delete_job(job_info):
    if  action_mgrs.has_key(job_info):
        del action_mgrs[job_info]

def delete_jobs(job_info_list):
    for job_info in job_info_list:
        delete_job(job_info)

class ActionMgr(object):
    def __init__(self):
        self.actions = []
        self.inds = {} # id:Individual
        self.last_act_id = 0
        self.last_updated_inds = {}

    def process_actions(self, new_actions):
        if len(new_actions) == 0: return
        self.last_updated_inds = {}
        
        for action in new_actions:
            assert isinstance(action, Action)
            self.last_act_id = max(self.last_act_id, action.get_id()) 
            inds = action.get_inds()
            for ind in inds:
                assert isinstance(ind, Individual)
                self.inds[ind._get_id()] = ind
                self.last_updated_inds[ind._get_id()] = ind            
        self.actions.extend(new_actions)

    def get_all_actions(self):
        return self.actions
    
    def get_last_updated_inds(self):
        return self.last_updated_inds.values()
    
    def get_inds(self):
        return self.inds.values()
    
    def get_action(self, _id):
        assert _id <= len(self.actions)
        return self.actions[_id - 1]
